package com.filyar.htyd.controller;

import com.alibaba.fastjson.JSONObject;
import com.filyar.htyd.common.Constants;
import com.filyar.htyd.common.Result;
import com.filyar.htyd.entity.config.WebhookConfig;
import com.filyar.htyd.service.IWebhookConfigService;
import com.filyar.htyd.utils.RedisUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: 非力亚-filyar
 * @Date: 2024/7/6 星期六  10:36
 * @Email: root@filyar.com
 */
@RestController
@RequestMapping("/config")
public class ConfigController {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IWebhookConfigService webhookConfigService;

    @GetMapping("/getWebhookConfig")
    public Result getWebhookConfig() {
        if (stringRedisTemplate.hasKey(Constants.WEBHOOK_CONFIG)){
            String valueFromRedis = redisUtils.getValueFromRedis(Constants.WEBHOOK_CONFIG);
            return Result.success(JSONObject.parseArray(valueFromRedis, WebhookConfig.class));
        }else {
            List<WebhookConfig> list = webhookConfigService.list();
            redisUtils.setValueToRedis(Constants.WEBHOOK_CONFIG, JSONObject.toJSONString(list));
            return Result.success(list);
        }
    }
    @PostMapping("/setWebhookConfig")
    public Result setWebhookConfig(@RequestBody WebhookConfig webhookConfig) {
        webhookConfigService.saveOrUpdate(webhookConfig);
        stringRedisTemplate.delete(Constants.WEBHOOK_CONFIG);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteWebhookConfig(@PathVariable Integer id) {
        webhookConfigService.removeById(id);
        stringRedisTemplate.delete(Constants.WEBHOOK_CONFIG);
        return Result.success();
    }
}
